package com.david.func_test.util

import android.animation.Animator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.marginBottom
import androidx.core.view.updateLayoutParams

class AnimUtil {
    companion object {
        /**
         * 底边距渐变
         */
        fun animBottomMargin(view: View, target: Int, endVisibleGone: Boolean = false, duration: Long = 200) {
            val marginBottom = view.marginBottom
            val valueAnimator = ValueAnimator.ofInt(marginBottom, target)
            valueAnimator.duration = duration
            valueAnimator.addUpdateListener { animator -> // 获得每次变化后的属性值
                val currentValue = animator.animatedValue as Int

                view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                    bottomMargin = currentValue
                }
            }
            if (endVisibleGone) {
                valueAnimator.doOnStart {
                    if (target > 0) {
                        view.visibility = View.VISIBLE
                    }
                }
                valueAnimator.doOnEnd {
                    if (target == 0) {
                        view.visibility = View.GONE
                    }
                }
            }
            valueAnimator.start()
        }

        /**
         * 渐变消失/显示
         */
        fun alphaShowHide(target: View, visible: Int) {
            val objectAnimator = if (target.visibility == View.VISIBLE) ObjectAnimator.ofFloat(target, View.ALPHA, 1f, 0f) else {
                target.visibility = View.VISIBLE
                ObjectAnimator.ofFloat(target, View.ALPHA, 0f, 1f)
            }
            objectAnimator.duration = 50
            objectAnimator.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {

                }

                override fun onAnimationEnd(animation: Animator) {
                    target.visibility = visible
                }

                override fun onAnimationCancel(animation: Animator) {

                }

                override fun onAnimationRepeat(animation: Animator) {

                }
            })
            objectAnimator.start()
        }
    }
}